package epk;/*
 * Copyright 2020 myepk.club All right reserved. This software is the
 * confidential and proprietary information of myepk.club ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with myepk.club
 */

import javax.sql.DataSource;
import java.sql.*;

/**
 * @author EPK
 * @date 2020/1/8 2:50
 */
public class DoSql {
    private static DataSource ds = null;
    private  Connection conn =  null;
    private  PreparedStatement  stmt =  null;
    private  ResultSet rs =  null;

    public static void setDataSource(Object dataSource){
        ds = (DataSource)dataSource;
    }

    public DoSql() throws SQLException {  //新建的对象都要创建连接
        conn = ds.getConnection();
    }

    public DoSql(String sql , Object[] objAry,boolean isQuery) throws SQLException {
        this();
        stmtSql(sql);
        doSql(objAry,isQuery);
    }

    public DoSql(String sql,boolean isQuery) throws SQLException {
        this(sql,null,isQuery);
    }

    public void stmtSql(String sql) throws SQLException {  //创建连接
        if(stmt != null) stmt.close();
        stmt = conn.prepareStatement(sql);
    }

    public void doSql( Object[] objAry,boolean isQuery) throws SQLException {  //执行SQL
        if(objAry != null){
            for(int i=0; i<objAry.length; i++){
                stmt.setObject( i+1, objAry[i]);
            }
        }
        if(isQuery){
            if(rs != null) rs.close();
            rs = stmt.executeQuery();
        }else
            stmt.executeUpdate();
    }

    public void doSql(boolean isQuery) throws SQLException {  //重载
        doSql(null, isQuery);
    }

    public String isExit(Object[] objAry) throws SQLException {  //判存
        doSql(objAry, true);
        if(rs == null || !rs.next()) //结果为空或者没有下一条。表明不存在！
            return "";
        else{
            rs.last();
            return rs.getString(1);
        }
    }

    public String isExit() throws SQLException {  //重载
        return isExit(null);
    }

    public ResultSet getResult(){
        return rs;
    }

    public void close() throws SQLException {
        if(rs != null) rs.close();
        if(stmt != null) stmt.close();
        if(conn != null) conn.close();
    }
}
